//@ts-nocheck
import { useRef, useState } from 'react'
import Chart from '@/components/Charts';
import { getRankOption } from '../options'
import { PrevIcon } from './PrevIcon'
import { NextIcon } from './NextIcon'
import styles from './index.module.less'

export const RankChart = ({
  height = 300,
  category = [],
  data = [],
  style,
  events = [],
  limit = 5,
  extra = {},
  option,
  ...restOptions
}) => {
  const visible = data?.length > limit;
  const chartRef = useRef(null);
  const totalRef = useRef(data?.length || 0);
  totalRef.current = data?.length || 0;
  const countRef = useRef(0);
  const [prevDisable, setPrevDisable] = useState(true);
  const [nextDisable, setNextDisable] = useState(false);

  const dispatchAction = () => {
    chartRef.current.current.dispatchAction({
      type: 'dataZoom',
      startValue: countRef.current,
      endValue: limit - 1 + countRef.current
    })
  }
  const excute = (type) => {
    if (type === 'prev') {
      // 'prev'
      if (prevDisable) return
      countRef.current -= limit // 下标自增
      setNextDisable(false)
      if (countRef.current === 0) {
        setPrevDisable(true)
      }
    } else {
      // 'next'
      if (nextDisable) return
      countRef.current += limit // 下标自增
      setPrevDisable(false)
      if (countRef.current + limit >= totalRef.current) {
        setNextDisable(true)
      }
    }
    dispatchAction()
  }

  return (
    <div className={styles.container} style={{ height, ...style }}>
      <Chart
        ref={chartRef}
        style={{ height: `calc(100% - ${visible ? 4 : 0}px)` }}
        option={option || getRankOption({
          category,
          data,
          limit,
          extra: {
            dataZoom: [
              //滑动条
              {
                yAxisIndex: 0, //这里是从X轴的0刻度开始
                show: false, //是否显示滑动条，不影响使用
                type: 'inside', // 这个 dataZoom 组件是 slider 型 dataZoom 组件 slide 显示 组件  inside 内置组件
                startValue: countRef.current, // 从头开始。
                endValue: limit - 1 + countRef.current, // 一次性展示4个。
                zoomOnMouseWheel: false
              }
            ],
            ...extra,
          },
          ...restOptions
        })}
        events={events}
      />
      {visible && (
        <div className={styles.btns}>
          <div
            className={styles.btn}
            onClick={() => excute('prev')}
            style={{ cursor: prevDisable ? 'not-allowed' : 'pointer' }}
          >
            <PrevIcon fill={!prevDisable ? '#6BA952' : '#D4D4D4'} />
          </div>
          <div
            className={styles.btn}
            onClick={() => excute('next')}
            style={{ cursor: nextDisable ? 'not-allowed' : 'pointer' }}
          >
            <NextIcon fill={!nextDisable ? '#6BA952' : '#D4D4D4'} />
          </div>
        </div>
      )}
    </div>
  )
}
